package com.wuhunyu.security;

import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;
import java.util.Date;

/**
 * token管理
 *
 * @author wuhunyu
 */
@Component
public class TokenManager {

    private static long TOKEN_EXPIRATION = 7 * 24 * 60 * 60 * 1000;

    private static String TOKEN_SIGN_KEY = "abcdefghigklmnopqlstuvwxyz";

    /**
     * 根据用户名生成token字符串
     * @param username
     * @return
     */
    public String createToken(String username) {
        return Jwts.builder().setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis() + TOKEN_EXPIRATION))
                .signWith(SignatureAlgorithm.HS512, TOKEN_SIGN_KEY).compressWith(CompressionCodecs.GZIP).compact();
    }

    /**
     * 根据token解析出用户名
     * @param token
     * @return
     */
    public String getUserFromToken(String token) {
        return Jwts.parser().setSigningKey(TOKEN_SIGN_KEY).parseClaimsJws(token).getBody().getSubject();
    }

}
